#! user/bin/python
# -*- coding: utf-8 -*-

"""
Created on 2021/8/26 15:00

@File: 关于email编码解码问题_解析器解码的要求.py
@Author: LT
@Description: poplib抓取邮件后生成的bytes字节串，必须要在email解析之前解码成str
"""
from email.mime.multipart import MIMEMultipart          # Message的子类
from email.mime.text import MIMEText                    # 提供更多题头+逻辑
from email.parser import Parser

top = MIMEMultipart()                                   # 跟Messgae对象
top['from'] = '284618025@qq.com'
top['to'] = '284618025@qq.com'

sub1 = MIMEText('nice red uniforms...\n')               # 组分Message的附件
sub2 = MIMEText(open('data.txt').read())
sub2.add_header('Content-Disposition', 'attachment', filename='data.txt')
top.attach(sub1)
top.attach(sub2)

text = top.as_string()                                  # 也可以str(top)或者print(top)
btext = text.encode()

msg1 = Parser().parsestr(text)                          # email解析器预期Unicode str
msg2 = Parser().parsestr(btext)                         # 不过poplib抓取的邮件为bytes，直接传入会报错！所以得像下面这样先解码才能传
msg3 = Parser().parsestr(btext.decode())
msg4 = Parser().parsestr(btext.decode('utf-8'))
msg5 = Parser().parsestr(btext.decode('latin-1'))
msg6 = Parser().parsestr(btext.decode('ascii'))

for each in msg1, msg3, msg4, msg5, msg6:
    print(each)
